from starlette.responses import RedirectResponse
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.routing import NoMatchFound
from fastapi import Request


# 关键：添加自动斜杠重定向中间件
class StripTrailingSlashMiddleware(BaseHTTPMiddleware):
    """
    中间件用于处理路径末尾斜杠问题
    当请求路径以斜杠结尾但无法匹配到对应路由时，自动去除末尾斜杠并重新尝试路由匹配
    """

    async def dispatch(self, request: Request, call_next):
        orig_path = request.url.path
        if orig_path == "/":
            return await call_next(request)
        try:
            # 尝试直接解析当前请求路径
            request.app.router.resolve(request.scope)
            return await call_next(request)
        except Exception:
            # 如果路由解析失败且路径以斜杠结尾
            if orig_path.endswith("/"):
                # 去掉末尾的 /
                new_path = request.url.path.rstrip("/")
                # 直接修改 scope，FastAPI 会用这个新路径去找路由
                request.scope["path"] = new_path # 如何用下面，这里要取消
                """
                new_scope = request.scope.copy()
                new_scope["path"] = new_path
                try:
                    request.app.router.resolve(new_scope)  # 再匹配
                    request.scope["path"] = new_path  # 静默改写
                except Exception:
                    pass
                """

        return await call_next(request)
